package com.jt.tenant.action;

import com.jt.tenant.app.JTApplication;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.utils.UrlSafeBase64;
import com.zcx.helper.http.Http;
import com.zcx.helper.secret.SecretHmacSHA1;
import com.zcx.helper.util.UtilToast;

import org.json.JSONObject;

import java.io.File;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by Administrator on 2016/3/4.
 */
public class QiNiuPictureUpload {

    private static final String ACCESS_KEY = "qALbVU5fU_QhKCccmJETYiUbpV35Ga-rf4vmzBU7";

    private static final String SECRET_KEY = "wfpZfHkyiPmoW6BgzY118IR4WzM5873JIi8EufDC";

    private static final String MAC_NAME = "HmacSHA1";

    private static final String ENCODING = "UTF-8";

    private QiNiuPictureUpload(){}

    public static void upload(File file, final OnPictureUploadCallBack onPictureUploadCallBack){

        try{

            String encodedPutPolicy = Http.getInstance().log("qiniu",  UrlSafeBase64.encodeToString(Http.getInstance().log("qiniu", new JSONObject().put("deadline", System.currentTimeMillis() / 1000 + 3600).put("scope", "test:" + file.getName()).toString()).getBytes()));

            String encodedSign = Http.getInstance().log("qiniu", UrlSafeBase64.encodeToString(new SecretHmacSHA1(SECRET_KEY).encrypt(encodedPutPolicy)));

            new UploadManager().put(file, file.getName(), ACCESS_KEY + ':' + encodedSign + ':'  + encodedPutPolicy,

                    new UpCompletionHandler() {

                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {

                            if(response != null) {

                                onPictureUploadCallBack.onSuccess(response.optString("key"));

                            }else {

                                UtilToast.show(JTApplication.mContext,"图片不可用，请选择其它图片或拍照");

                            }

                        }

                    }, null);

        }catch (Exception e){}

    }

    private static byte[] hmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {

        byte[] data = encryptKey.getBytes(ENCODING);

        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);

        Mac mac = Mac.getInstance(MAC_NAME);

        mac.init(secretKey);

        byte[] text = encryptText.getBytes(ENCODING);

        return mac.doFinal(text);

    }

    public interface OnPictureUploadCallBack{

        void onSuccess(String imageUrl);

    }

}
